import Dialog from '@/composables/dialog'
import { http } from '@/utils/http'
import { isApp } from './platform'
// 类型定义
type Platform = 'ios' | 'android' | 'other'
type UpdateType = 'sdk' | 'wgt'
type ForceUpdateType = 1 | 2 // 1: 非强制, 2: 强制
type HotUpdateType = '0' | '1' // 0: 静默更新, 1: 弹窗提示

interface VersionInfo {
  version: string
  description: string
  download_url: string
  force_update_type: ForceUpdateType
  hot_update_type: HotUpdateType
  sdk_update_type: 1 | 2 // 1: wgt更新, 2: sdk更新
}

interface AppVersionResponse {
  sdk_version?: VersionInfo
  wgt_version?: VersionInfo
}

interface AppInfo {
  versionCode: string
}

/**
 * 解析版本号字符串为数字数组
 * @param versionString 版本号字符串 (如 "1.2.3")
 * @returns 版本号数字数组 (如 [1, 2, 3])
 */
function parseVersion(versionString?: string): number[] {
  if (!versionString) return []
  return versionString.split('.').map(Number)
}

/**
 * 比较版本号是否需要更新
 * @param currentVersion 当前版本号数组
 * @param latestVersion 最新版本号数组
 * @returns 是否需要更新
 */
function isNewVersionAvailable(currentVersion: number[], latestVersion: number[]): boolean {
  for (let i = 0; i < Math.max(currentVersion.length, latestVersion.length); i++) {
    const current = currentVersion[i] || 0
    const latest = latestVersion[i] || 0
    if (current < latest) return true
    if (current > latest) return false
  }
  return false
}

/**
 * 格式化更新日志
 * @param description 原始更新日志描述
 * @returns 格式化后的更新日志
 */
function formatUpdateLog(description: string): string {
  try {
    return description.split('|').join('\n')
  } catch (e) {
    console.error('格式化更新日志失败:', e)
    return description
  }
}

/**
 * 打开应用商店 (iOS专用)
 * @param downloadUrl 下载地址或Apple ID
 */
function openAppStore(downloadUrl: string): void {
  const appleId = downloadUrl.match(/id(\d+)/)?.[1] || downloadUrl
  plus.runtime.launchApplication(
    {
      action: `itms-apps://itunes.apple.com/cn/app/id${appleId}?mt=8`,
    },
    (e) => {
      console.error('打开应用商店失败:', e.message)
      uni.showToast({ title: '无法打开应用商店', icon: 'none' })
    },
  )
}

/**
 * 安装更新包
 * @param downloadTask 下载任务对象
 * @param status 下载状态
 * @param isSilent 是否静默更新
 */
function installUpdate(downloadTask: any, status: number, isSilent = false): void {
  if (status !== 200) {
    !isSilent && uni.showToast({ title: '下载更新失败', icon: 'none' })
    return
  }

  plus.runtime.install(
    downloadTask.filename,
    {
      force: false,
    },
    () => {
      if (!isSilent) {
        plus.nativeUI.closeWaiting()
        Dialog.show({
          title: '更新完成',
          content: '应用已更新完成，需要重启生效',
          confirmText: '立即重启',
          showCancel: false,
          confirm: () => plus.runtime.restart(),
        })
      }
    },
    (error) => {
      !isSilent && plus.nativeUI.closeWaiting()
      console.error('安装失败:', error)
      Dialog.show({
        title: '安装失败',
        content: `无法安装更新包: ${error.message}`,
        confirmText: '确定',
        showCancel: false,
      })
    },
  )
}

/**
 * 开始下载更新包
 * @param downloadUrl 下载地址
 * @param isSilent 是否静默更新
 */
function startDownload(downloadUrl: string, isSilent = false): void {
  console.log('开始下载更新包:', downloadUrl)

  const downloadTask = plus.downloader.createDownload(downloadUrl, {}, (task, status) =>
    installUpdate(task, status, isSilent),
  )

  try {
    downloadTask.start()

    if (!isSilent) {
      const loading = plus.nativeUI.showWaiting('正在下载更新')
      let progress = 0

      downloadTask.addEventListener('statechanged', (task) => {
        switch (task.state) {
          case 3: // 下载中
            progress = Math.floor((task.downloadedSize / task.totalSize) * 100)
            loading.setTitle(`下载中 ${progress}%`)
            break
          case 4: // 完成
            plus.nativeUI.closeWaiting()
            break
        }
      })
    }
  } catch (error) {
    !isSilent && plus.nativeUI.closeWaiting()
    console.error('下载失败:', error)
    uni.showToast({ title: '下载更新失败', icon: 'none' })
  }
}

/**
 * 检查应用更新
 * @param isUserInitiated 是否用户主动触发检查
 * @returns Promise 返回更新状态
 */
export function checkAppUpdate(isUserInitiated = false): Promise<string> {
  // 非App平台直接返回不处理
  if (!isApp) return Promise.resolve('no-update')
  return new Promise((resolve) => {
    // 获取系统信息
    const systemInfo: UniNamespace.GetSystemInfoResult = uni.getSystemInfoSync()
    const { platform, appVersion, appWgtVersion } = systemInfo
    console.log(systemInfo, 'systemInfo')

    // 获取当前版本信息
    const currentSdkVersion = parseVersion(appVersion)
    const currentWgtVersion = parseVersion(appWgtVersion)

    // 请求最新版本信息
    http
      .get<AppVersionResponse>('/app/version/latest/type', {
        platform: platform === 'ios' ? 2 : 1,
        app_package_name: 'com.ludaxi.hw.privatesphere',
      })
      .then((res) => {
        if (!res.data.sdk_version && !res.data.wgt_version) {
          return resolve('no-update')
        }

        plus.runtime.getProperty(plus.runtime.appid, (appInfo: AppInfo) => {
          // 解析接口返回的最新版本
          const latestSdkVersion = parseVersion(res.data.sdk_version?.version)
          const latestWgtVersion = parseVersion(res.data.wgt_version?.version)
          console.log(currentSdkVersion, latestSdkVersion, 'sdkversion')
          console.log(currentWgtVersion, latestWgtVersion, 'wgtversion')

          // 确定需要更新的版本类型
          let updateType: UpdateType | null = null
          let versionData: VersionInfo | null = null
          console.log(isNewVersionAvailable(currentSdkVersion, latestSdkVersion), 'sdk')
          console.log(isNewVersionAvailable(currentWgtVersion, latestWgtVersion), 'wgt')

          if (isNewVersionAvailable(currentSdkVersion, latestSdkVersion)) {
            updateType = 'sdk'
            versionData = res.data.sdk_version!
          } else if (isNewVersionAvailable(currentWgtVersion, latestWgtVersion)) {
            updateType = 'wgt'
            versionData = res.data.wgt_version!
          }

          // 需要更新
          if (updateType && versionData) {
            console.log('发现新版本:', versionData.version)

            // 静默更新
            if (versionData.hot_update_type === '0') {
              startDownload(`https://store.ssccn.cn${versionData.download_url}`, true)
              return resolve('silent-update-started')
            }

            // 显示更新弹窗
            Dialog.show({
              title: `发现新版本 ${versionData.version}`,
              content: versionData.description
                ? formatUpdateLog(versionData.description)
                : '暂无更新说明',
              confirmText: '立即更新',
              showCancel: versionData.force_update_type === 1,
              cancelText: '以后再说',
              confirm: () => {
                if (platform === 'ios' && versionData!.sdk_update_type === 2) {
                  openAppStore(versionData!.download_url)
                  plus.runtime.quit()
                } else {
                  startDownload(`https://store.ssccn.cn${versionData!.download_url}`)
                }
              },
              cancel: () => {
                // 用户主动检查但取消更新时，如果是SDK更新且非强制，静默更新WGT包
                if (
                  isUserInitiated &&
                  updateType === 'sdk' &&
                  versionData!.force_update_type === 1
                ) {
                  startDownload(`https://store.ssccn.cn${versionData!.download_url}`, true)
                }
              },
            })

            return resolve('update-available')
          }

          // 无需更新
          resolve('no-update')
        })
      })
      .catch((error) => {
        console.error('检查更新失败:', error)

        // 网络错误时提示用户
        Dialog.show({
          title: '网络错误',
          content: '无法检查更新，请检查网络连接',
          confirmText: '重试',
          showCancel: true,
          cancelText: '取消',
          confirm: () => checkAppUpdate(isUserInitiated),
          cancel: () => resolve('network-error'),
        })
      })
  })
}
